import datetime
import uuid
from django.db.models import Q
from django.shortcuts import render, HttpResponse, redirect
from django.http import JsonResponse
from web.forms.account import RegisterModelForm, SendSmsForm, LoginSmsForm, LoginForm
from web import models
from utils.image_code import check_code
from io import BytesIO


def register(request):
    if request.method == 'GET':
        form = RegisterModelForm()
        return render(request, 'register.html', {'form': form})
    print(request.POST)
    form = RegisterModelForm(data=request.POST)
    if form.is_valid():
        # 验证通过，写入数据库
        # 自动剔除数据库中没有的字段
        # 数据库中的密码处理为密文，进行加密处理(通过RegisterModelForm对密码进行加密处理)
        instance = form.save()
        # instance就是当前注册成功的对象（包含注册的所有字段）
        # 创建交易记录
        policy_object=models.PricePolicy.objects.filter(category=1,title='个人免费版').first()
        models.Transaction.objects.create(status=2,order=uuid.uuid4(),user=instance,price_policy=policy_object,count=0,price=0,start_datetime=datetime.datetime.now())
        return JsonResponse({'status': True, 'data': '/login'})
    else:
        return JsonResponse({'status': False, 'error': form.errors})


def send_sms(request):
    print(request.GET)
    form = SendSmsForm(request, data=request.GET)
    if form.is_valid():
        return JsonResponse({'status': True})
    return JsonResponse({'status': False, 'error': form.errors})


def login_sms(request):
    """ 短信登录 """
    if request.method == 'GET':
        form = LoginSmsForm()
        return render(request, 'login_sms.html', {'form': form})

    form = LoginSmsForm(request.POST)
    if form.is_valid():
        # 用户输入正确，登录成功
        mobile_phone = form.cleaned_data['mobile_phone']
        # 用户信息放入session
        user_obj = models.UserInfo.objects.filter(mobile_phone=mobile_phone).first()
        request.session['user_id'] = user_obj.id
        request.session['user_name'] = user_obj.username

        return JsonResponse({'status': True, 'data': '/index/'})
    return JsonResponse({'status': False, 'error': form.errors})


def login(request):
    """ 用户名和密码登录 """
    if request.method == 'GET':
        form = LoginForm(request)
        return render(request, 'login.html', {'form': form})
    form = LoginForm(request, data=request.POST)
    if form.is_valid():
        username = form.cleaned_data['username']
        password = form.cleaned_data['password']
        user_obj = models.UserInfo.objects.filter(Q(Q(mobile_phone=username) | Q(email=username))).filter(
            password=password).first()
        if not user_obj:
            form.add_error('username', '用户名或密码错误')
            return render(request, 'login.html', {'form': form})
        # 登录成功，获取ID，并设置超时时间
        request.session['user_id'] = user_obj.id
        request.session.set_expiry(60 * 60 * 24 * 14)
        return redirect('/index/')
    return render(request, 'login.html', {'form': form})


def image_code(request):
    """ 生成图片验证码 """
    image_object, code = check_code()

    # 将验证码存入session,并设置过期时间
    request.session['image_code'] = code
    request.session.set_expiry(60)

    # 将图片存入到内存中，并返回给用户
    stream = BytesIO()
    image_object.save(stream, 'png')
    return HttpResponse(stream.getvalue())


def logout(request):
    request.session.flush()
    return redirect('web:index')
